package CCRMServer.Controllers;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import CCRMServer.DBConnect;
import Common.Entities.Employee;
import Common.Entities.STATUS;
/**
 * This class implements user's verification in the DB
 * @author ori ziv
 *
 */
public class UserVerify {
	/**
	 * This method query the DB and get user's data to register.
	 * @param userName - user's login name
	 * @param password - user's login password
	 * @return -
	 * 			null in case of DB error
	 * 			empty Employee object if user name is invalid
	 * 			Employee object with only user name in case password is invalid
	 * 			a full Employee object if everything is OK
	 */
	public static Employee registerUser (String userName, char[] password) {
		Employee user = new Employee ();
		String filter = "employeeUserName = '" + userName + "'";
		Connection conDB = DBConnect.mySQLConnection();
		try {
			// query DB
			ResultSet rs = DBConnect.selectWithFilter(conDB, "Employees", null, filter);
			if (rs.next()) {
				if (userName.equals(rs.getString(8))) {					// verify user name
					user.setUserName(userName);							// if user name is OK set user name to object
					String pswd = new String(password);
					if (pswd.equals(rs.getString(9))) {				// verify password
						user.setPassword(password);						// if everything is OK fill object
						user.setID(rs.getString(1));
						user.setName(rs.getString(2));
						user.setBithday(rs.getDate(3));
						user.setPhone(rs.getString(4));
						user.setPosition(rs.getString(5));
						user.setDepartment(rs.getString(6));
						int stat = rs.getInt(7);
						if (stat == 1) user.setStatus(STATUS.ACTIVE);
						else if (stat == 2) user.setStatus(STATUS.SUSPENDED);
						else user.setStatus(STATUS.NOT_ACTIVE);
					}
				}
			}
		} catch (SQLException e) {
			return null;												// in case of exception - return null
		}
		return user;
	}

}
